#!/usr/bin/env python
# -*- coding: utf-8 -*- 

#Kiwi Bot
#Make by @nge1nCorsic4 in 2011
#Modified by @nge1nCorsic4 in 2012
#This program is free software; you can redistribute it and/or modify
#it under the terms of the GNU General Public License as published by
#the Free Software Foundation; either version 2 of the License, or
#(at your option) any later version.

#This program is distributed in the hope that it will be useful,
#but WITHOUT ANY WARRANTY; without even the implied warranty of
#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
#GNU General Public License for more details.

#You should have received a copy of the GNU General Public License along
#with this program; if not, write to the Free Software Foundation, Inc.,
#51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

import kiwi, kiwi.plugin, kiwi.events, kiwi.config, kiwi.lang
import glob, threading, os, re, time

class map(kiwi.plugin.Plugin):
	def onStart(self):
		self.lang = kiwi.lang.Lang(self,'map')
		ServNumber = kiwi.config.configuration().kiwi.kiwidir
		self.conf = kiwi.config.configuration('@kiwi/conf/'+ServNumber+'/map.cfg')
		self.advanced_function = kiwi.getPath(self.conf.settings.advanced_function)
		self.PubMap = kiwi.getPath(self.conf.settings.pub_map)
		self.time = int(self.conf.settings.time)
		self.register = self.main.getPlugin('admin').mod.registerCommand
		self.register('map', int(self.conf.levels.map), self._map, "000801")
		self.register('nextmap', int(self.conf.levels.nextmap), self._nextmap, "000802")
		self.register('cyclemap', int(self.conf.levels.cyclemap), self._cyclemap, "000800")
		if self.advanced_function == 'on' :
			self.register('forcemap', int(self.conf.levels.map), self._forcemap, "000801")
			self.register('devmap', int(self.conf.levels.devmap), self._devmap, "000803")
			self.register('listmap', int(self.conf.levels.listmap), self._listmap, "000807")
		self.registerEvent(kiwi.events.EVT_GAME_START, self.checkMap)
		self.init()
	def onStop(self):
		self.main.getPlugin('admin').mod.deleteCommand('map')
		self.main.getPlugin('admin').mod.deleteCommand('nextmap')
		self.main.getPlugin('admin').mod.deleteCommand('cyclemap')
		self.start = False
		if self.advanced_function == 'on' :
			self.main.getPlugin('admin').mod.deleteCommand('forcemap')
			self.main.getPlugin('admin').mod.deleteCommand('devmap')
			self.main.getPlugin('admin').mod.deleteCommand('listmap')
	def init(self, init=None):
		if not init:
			threading.Timer(15, self.init, [True]).start()
		else:
			self.current_map = None
			self.CycleList = None
			self.nextmap = None
			self.source = None
			self.start = True
			self.checkSource()
			self.GetAllmap()
			if self.PubMap == 'on' :
				self.ViewMap()
	def checkSource(self):
		if not self.source:
			try:
				source = []
				p = self.output.send('fs_basepath')
				p = p.split('"')[3]
				p = p.split('^')[0]
				self.s = p+'/q3ut4/'
				if os.path.isdir(self.s):
					source.append(self.s)
				Game_Source = kiwi.config.configuration().server.log_game
				Game_Source = Game_Source.split('q3ut4')[0]
				source.append(Game_Source+'q3ut4/')
				self.source = source
			except:
				threading.Timer(5,self.checkSource).start()
				print 'check source not good'
	def checkMap(self,event):
		self.current_map = event.vars['mapname']
		self.nextmap = None
	def GetAllmap(self):
		t = self.ReadFile(kiwi.getPath('@kiwi/files/officiel.txt'))
		path = self.source
		if path :
			for p in path:
				files = '*.pk3'
				Maps = glob.glob(p+files)
				for f in Maps:
					a = f.split("/")
					d = a[-1]
					if not 'zpak' in d[0:4] :
						t.append(d[:-4]+'\n')
		self.list = t
	def getmaps(self, event):
		argu = event.arguments[0]
		t = self.list
		nb = 0
		for txt in t:
			if argu in txt:
				nb = nb+1
		if nb == 0:
			return '^4%s'%(self.lang.lang(event,'00807'))
		elif nb == 1:
			for txt in t:
				if argu in txt:
					return [txt]
		elif nb > 1 and nb <= 30:
			if len(event.arguments) > 1 :
				for txt in t:
					# print argu, len(argu), type(argu), txt[:-1], len(txt[:-1]), type(txt[:-1])
					if argu == txt[:-1]:
						return [txt]
				self.output.tell(event.id,self.lang.lang('','00820'))
				event.arguments.remove(event.arguments[1])
			message = ('^4%s '%(self.lang.lang(event,'00818')))
			for txt in t:
				if argu in txt:
					message += ' ^3%s ^1| '%(txt[:-1])
			return message[:-2]+'.'
		else:
			return '^4%s'%(self.lang.lang(event,'00808'))
	def checkCycle(self):
		try:
			# self.output.send('g_mapcycle')
			# time.sleep(0.3)
			mapcycle = self.output.send('g_mapcycle')
			mapcycle = mapcycle.split('"')
			self.m = mapcycle[3]
			# path = self.source
			if self.source:
				for p in self.source:
					if os.path.isfile(p+self.m):
						CycleList = self.ReadFile(p+self.m)
						list = []
						for m in CycleList :
							if re.match("^[ut(0-9)+_]+[A-Za-z0-9-]*[_]+[A-Za-z0-9-]*$",m):
								list.append(m)
							elif re.match("^[A-Za-z0-9]*$",m):
								list.append(m)
						self.CycleList = list
		except Exception:
			threading.Timer(5,self.checkCycle).start()
			print mapcycle
	def ViewMap(self):
		if self.current_map:
			if self.start :
				if self.nextmap :
					self.output.send('^4map: ^2%s ^4- Next :^2%s'%(self.current_map,self.nextmap))
				else:
					if self.CycleList :
						nb = 0
						for m in self.CycleList:
							m = m.split()[0]
							if nb == 0:
								self.nextmap = m
								nb = 1
							if m == self.current_map:
								nb = 2
							elif nb == 2 :
								self.output.send('^4map: ^2%s ^4- Next :^2%s'%(self.current_map,m))
								self.nextmap = m
								break
					else:
						self.checkCycle()
		threading.Timer(self.time, self.ViewMap).start()
	def ReadFile(self, source):
		f = file(source,'r')
		list = f.readlines()
		f.close()
		return list
	def message(self, event):
		if len(event.arguments) > 0:
			message = self.getmaps(event)
			if len(message) == 1:
				self.output.tell(event.id, '^4%s ^3%s'%(self.lang.lang(event,'00819'), message[0]))
				return message[0]
			else:
				self.output.tell(event.id, message)
				return False
		else:
			self.output.tell(event.id, self.lang.lang(event,'00101'))
			return False
	def _cyclemap(self, event):
		self.output.send('cyclemap')
	def _map(self, event):
		if len(event.arguments) > 0:
			message = self.message(event)
			if message :
				self.output.send('map %s'%message)
		else:
			self.output.tell(event.id,'^4CurrentMap : ^2%s'%self.current_map)
	def _forcemap(self, event):
		event.arguments.append('force')
		message = self.message(event)
		if message :
			self.output.send('map %s'%message)
	def _nextmap(self, event):
		if len(event.arguments) > 0:
			message = self.message(event)
			if message :
				self.output.send('g_nextmap %s'%message)
				self.nextmap = message
		else:
			self.output.tell(event.id,'^4NextMap : ^2%s'%self.nextmap)
	def _devmap(self, event):
		message = self.message(event)
		if message :
				self.output.send('devmap %s'%message)
	def _listmap(self, event):
		if len(event.arguments) > 0:
			self.message(event)
		else:
			list = ''
			if self.CycleList:
				for n in self.CycleList:
					list+= ' ^3%s ^1| '%(n[:-1])
				list = list[:-2]+'.'
				self.output.tell(event.id, '^4%s %s'%(self.lang.lang(event,'00819'),list))
			else:
				self.output.tell(event.id, self.lang.lang(event,'00820'))
				self.checkCycle()
				self._listmap(event)
